
Queries can be converted to scalar queries. This can be necessary when a query is guaranteed to return a single value and that value has to be used in e.g. a predicate. To convert a query to a scalar query, use any of the following methods
To enforce a row limit, the method .ForceRowLimit() can be called on a scalar query expression. Row limits are required if the scalar query can potentially return multiple elements and just 1 element is required.
Fetching scalar queries is possbly by using a wrapping Select() call. Below are several examples of constructing and fetching scalar queries directly.
var qf = new QueryFactory();
// Scalar query which fetches a boolean using Any().
var q = qf.Create().Select(qf.Customer.Where(CustomerFields.CustomerId == "CHOPS").Any());
// Adapter
var exists = adapter.FetchScalar<bool>(q);
// SelfServicing
// var exists = new TypedListDAO().GetScalar<bool>(q, null);
// Another scalar query using Any() fetching a boolean.
var q = qf.Create()
.Select(qf.Customer.Where(CustomerFields.Country=="Germany")
.Any(CustomerFields.CustomerId=="ALFKI"));
// Adapter
var exists = adapter.FetchScalar<bool>(q);
// SelfServicing
// var exists = new TypedListDAO().GetScalar<bool>(q, null);
// Fetching the total of all orders.
var q = qf.Create()
.Select(qf.Customer.As("C")
.Select(CustomerFields.CustomerId,
qf.Order
.CorrelatedOver(OrderEntity.Relations.CustomerEntityUsingCustomerId)
.Select(qf.OrderDetail
.CorrelatedOver(OrderDetailEntity.Relations.OrderEntityUsingOrderId)
.Select(OrderDetailFields.Quantity * OrderDetailFields.UnitPrice)
.Sum().As("OrderTotal"))
.Sum().As("TotalAllOrders"))
.Max());
// Adapter.
var result = adapter.FetchScalar<decimal>(q);
// SelfServicing
// var result = new TypedListDAO().GetScalar<decimal>(q, null);
// Fetching the rowcount of a query defined separately.
var q = qf.Create()
.Select(CustomerFields.CustomerId, CustomerFields.CompanyName,
OrderFields.OrderId, OrderFields.OrderDate)
.From(qf.Customer.InnerJoin(CustomerEntity.Relations.OrderEntityUsingCustomerId));
// Adapter.
var count = adapter.FetchScalar<int>(qf.Create().Select(q.CountRow()));
// SelfServicing
// var count = new TypedListDAO().GetScalar<int>(qf.Create().Select(q.CountRow()), null);